/*
 * Copyright (c) 2019. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package cn.dyw.player;

import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class ImageUtils {

    /**
     * 合并图片
     * @param bufferedImage
     * @return
     * @throws IOException
     */
    public static BufferedImage mergeImage(BufferedImage bufferedImage) throws IOException {
        BufferedImage image = Thumbnails.of(bufferedImage).size(270, 270).asBufferedImage();
        BufferedImage result = Thumbnails.of(ImageUtils.class.getClassLoader().getResourceAsStream("border.png"))
                .scale(1.0f).watermark(Positions.CENTER, circularImage(image), 1).asBufferedImage();
        return result;
    }

    /**
     * 剪裁圆形图片
     * @param image
     * @return
     */
    public static BufferedImage circularImage(BufferedImage image) {
        BufferedImage resultImg = null;

        resultImg = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resultImg.createGraphics();
        Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, image.getWidth(), image.getHeight());
        // 使用 setRenderingHint 设置抗锯齿
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        resultImg = g.getDeviceConfiguration().createCompatibleImage(image.getWidth(), image.getHeight(),
                Transparency.TRANSLUCENT);

        g = resultImg.createGraphics();

        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setClip(shape);
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return resultImg;
    }
}
